﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using WoSai.Base.Common;
namespace WoSai.Base.Config
{
    class DefaultConfigFileManager : BaseConfigFileManager
    {
        private static IConfigInfo configInfo;
        private static object locker = new object();
        private static DateTime filechangetime;
        private static string filename = null;
        static DefaultConfigFileManager()
        {
            filechangetime = System.IO.File.GetLastWriteTime(ConfigFilePath);
            configInfo = (DefaultConfigInfo)BaseConfigFileManager.DeserializeConfig(ConfigFilePath, typeof(DefaultConfigInfo));
        }
        public new static IConfigInfo ConfigInfo
        {
            get { return configInfo; }
            set { configInfo = (DefaultConfigInfo)value; }
        }
        public new static string ConfigFilePath
        {
            get
            {
                if (filename == null)
                {
                    HttpContext context = HttpContext.Current;
                    if (context != null)
                    {
                        filename = context.Server.MapPath("~/WoSai.config");
                        if(!File.Exists(filename))
                        {
                            filename=context.Server.MapPath("/WoSai.config");
                        }
                    }
                    else
                    {
                        filename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WoSai.config");
                    }
                    if (!File.Exists(filename))
                    {
                        throw new WoSaiException("发生错误: 虚拟目录或网站根目录下不存在WoSai.config文件");
                    }
                }
                return filename;
            }
        }
        public static DefaultConfigInfo LoadCachedConfig()
        {
            configInfo = BaseConfigFileManager.LoadConfig(ref filechangetime, ConfigFilePath, ConfigInfo);
            return configInfo as DefaultConfigInfo;
        }
        public static DefaultConfigInfo LoadFileConfig()
        {
            configInfo = BaseConfigFileManager.LoadConfig(ref filechangetime, ConfigFilePath, ConfigInfo, false);
            return configInfo as DefaultConfigInfo;
        }
        public bool SaveConfig()
        {
            return base.SaveConfig(ConfigFilePath, ConfigInfo);
        }
    }
}
